#include "qmidinote.h"
#include "qmidihelper.h"
#include "allegro.h"
#include <QFileInfo>
#include <QHeaderView>

using namespace midiHelper;

QMidiNote::QMidiNote(QWidget *parent)
	: QTableWidget(parent)
{
	auto size = QSize(800, 400);
	resize(size);

	QStringList header;
	header << "Trk" << "HMSF" << "MBT" << "Ch" << "Kind" << "Data" << "Volume" << "Dur";
	setColumnCount(header.size());
	setHorizontalHeaderLabels(header);

	horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
	//verticalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents);
	setEditTriggers(QAbstractItemView::NoEditTriggers);
}

QMidiNote::~QMidiNote()
{
}

void QMidiNote::open(const QString& path)
{
	if (path.isEmpty())
	{
		Q_ASSERT(false);
		return;
	}

	QFileInfo fileInfo(path);
	if (!fileInfo.isFile())
	{
		Q_ASSERT(false);
		return;
	}

	Alg_seq seq(path.toStdString().c_str(), true);
	Alg_seq_ptr new_seq = &seq;
	if (new_seq->get_read_error() != alg_no_error)
	{
		Q_ASSERT(false);
		return;
	}

	clearContents();
	setRowCount(0);

	auto& notes = getNoteEvents(new_seq);
	if (notes.size() < 1)
	{
		return;
	}

	setRowCount(notes.size());

	int iRow = 0;
	for (auto& note : notes)
	{
		int iCol = 0;

		// Trk
		QString Trk = QString("%1").arg(note.track);
		setItem(iRow, iCol, new QTableWidgetItem(Trk));
		this->item(iRow, iCol)->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
		++iCol;

		// HMSF
		QString HMSF = note.HMSF;
		setItem(iRow, iCol, new QTableWidgetItem(HMSF));
		this->item(iRow, iCol)->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
		++iCol;

		// MBT
		QString MBT = note.MBT;
		setItem(iRow, iCol, new QTableWidgetItem(MBT));
		this->item(iRow, iCol)->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
		++iCol;

		// Ch
		QString ch = QString("%1").arg(note.channel);
		setItem(iRow, iCol, new QTableWidgetItem(ch));
		this->item(iRow, iCol)->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
		++iCol;
		
		// Kind
		QString Kind("Note");
		setItem(iRow, iCol, new QTableWidgetItem(Kind));
		this->item(iRow, iCol)->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
		++iCol;

		// Data
		QString Data(note.data);
		setItem(iRow, iCol, new QTableWidgetItem(Data));
		this->item(iRow, iCol)->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
		++iCol;

		// Volume
		QString Volume = QString("%1").arg(note.level);
		setItem(iRow, iCol, new QTableWidgetItem(Volume));
		this->item(iRow, iCol)->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
		++iCol;

		// Dur
		QString Dur(note.Dur);
		setItem(iRow, iCol, new QTableWidgetItem(Dur));
		this->item(iRow, iCol)->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
		++iCol;

		++iRow;
	}
}
